from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse_lazy, reverse
from django.views.decorators.http import require_http_methods, require_POST, require_GET

from blog.forms import PubBlogForm
from blog.models import BlogCategory, Blog, BlogComment


# Create your views here.
def index(request):
    # 这个查询会带limit
    blogs = Blog.objects.order_by('-pub_time')[:6]
    return render(request, 'index.html', {'blogs': blogs})


def detail(request, blog_id):
    try:
        blog = Blog.objects.get(pk=blog_id)
    except Exception as e:
        print(e)
        blog = None
    return render(request, 'blog_detail.html', context={'blog': blog})


# 两种三种写法
# @login_required(login_url=reverse_lazy("zlauth:login"))
# @login_required(login_url='/auth/login')
# 最下面一种需要在配置文件中配置login_url
@login_required()
@require_http_methods(['GET', 'POST'])
def pub_blog(request):
    if request.method == 'GET':
        categories = BlogCategory.objects.all()
        return render(request, 'pub_blog.html', context={'categories': categories})
    else:
        pass
        form = PubBlogForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data['title']
            content = form.cleaned_data['content']
            category_id = form.cleaned_data['category']
            blog = Blog.objects.create(title=title, content=content, category_id=category_id, author=request.user)
            return JsonResponse({'code': '200', "message": "success", "data": blog.id})
        else:
            print(form.errors)
            return JsonResponse({'code': '400', "message": "failed"})


@require_POST
@login_required()
def pub_comment(request):
    blog_id = request.POST.get('blog_id')
    content = request.POST.get('content')
    save = BlogComment.objects.create(blog_id=blog_id, content=content, author=request.user)
    if save:
        print(f"保存评论成功")
    # 重新加载博客详情页面
    return redirect(reverse('blog:detail', kwargs={'blog_id': blog_id}))


@require_GET
def search(request):
    keyword = request.GET.get('keyword')
    # 从博客的标题和内容中查找关键字的博客
    blogs = Blog.objects.filter(Q(title__icontains=keyword) | Q(content__icontains=keyword)).all()
    return render(request, 'index.html', context={'blogs': blogs})
